package com.example.musicplayer.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.musicplayer.R;
import com.example.musicplayer.dialogTools.NormalAlertDialog;
import com.example.musicplayer.musicClass.MusicInfo;
import com.example.musicplayer.musicClass.MusicMenu;
import com.example.musicplayer.settings.MusicPlayerSettings;
import com.example.musicplayer.view.MusicMenuSimpleDisplay;
import com.example.musicplayer.view.NewScrollView;
import com.example.musicplayer.view.SimpleDisplayView;
import com.example.musicplayer.viewTools.AdjustViewOrder;
import com.example.musicplayer.windowTools.WindowTools;

import java.util.ArrayList;
import java.util.List;

public class MusicMenuManageActivity extends BaseActivity implements MusicMenuSimpleDisplay.CallBack {
    public static final int RESULT_CODE = 300;
    public static final String CONFIRM_CODE = "from";
    public static final String DEFAULT_SELECTED = "defaultSelected";
    private TextView mTextViewConfirm;
    private LinearLayout mContainer;
    private LinearLayout mAdjustOrderArea;
    private Button mButtonDelete;
    private List<MusicMenu> mMusicMenus = new ArrayList<MusicMenu>();
    private final List<MusicMenuSimpleDisplay> mDisplay = new ArrayList<MusicMenuSimpleDisplay>();
    private boolean mStateChanged = false;
    private boolean mNeedUpdate = true;
    private String mFrom;
    //按下调整顺序按键时的y坐标
    private float mStartY;
    //调整顺序按下的view的编号
    private int mTargetNumber;
    //调整顺序的管理类
    private AdjustViewOrder mAdjustViewOrder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_menu_manage);
        WindowTools.lightStatusBar(getWindow());

        Intent intent = getIntent();
        mFrom = intent.getStringExtra(CONFIRM_CODE);
        initView();
        addListener();
        updateView();
        for (int i = mMusicMenus.size() - 1; i >= 0; i--) {
            addNewMusicMenuView();
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && mNeedUpdate) {
            updateMusicMenuView();
            //scroll to default selected position
            int selected = getIntent().getIntExtra(DEFAULT_SELECTED, -1);
            if (selected >= 0 && selected < mDisplay.size()) {
                mDisplay.get(selected).getView().performClick();
                ((NewScrollView) findViewById(R.id.scroll_view_music_menu_manage)).scrollBy(0
                        , mDisplay.get(0).getViewHeight() * selected);
            }
            //set as default
            getIntent().putExtra(DEFAULT_SELECTED, -1);
            mNeedUpdate = false;
        }
    }

    @Override
    public void onBackPressed() {
        finishToBack();
        super.onBackPressed();
        setPendingTransition(R.anim.fake_anim, R.anim.activity_vertical_exit);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finishToBack();
            finish();
            setPendingTransition(R.anim.fake_anim, R.anim.activity_vertical_exit);
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar_music_menu_manage);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            //添加向上操作
            actionBar.setDisplayHomeAsUpEnabled(true);
            //去除toolbar中的标题
            actionBar.setDisplayShowTitleEnabled(false);
        }
        mTextViewConfirm = findViewById(R.id.textview_music_menu_manage_confirm);
        mContainer = findViewById(R.id.linear_layout_delete_music_menu_container);
        mAdjustOrderArea = findViewById(R.id.linear_layout_adjust_order);
        mButtonDelete = findViewById(R.id.button_delete);
        mMusicMenus = MusicInfo.getMusicMenus();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void addListener() {
        findViewById(R.id.button_music_menu_manage_recover).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickRecover();
            }
        });
        findViewById(R.id.linear_layout_delete_music_menu).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickDelete();
            }
        });
        mButtonDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickDelete();
            }
        });
        mTextViewConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickConfirm();
            }
        });
        mAdjustOrderArea.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                float y = event.getY();
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mStartY = y;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        mAdjustViewOrder.adjustView(mStartY, y, true);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        //获取结束时的位置
                        int endNumber = mAdjustViewOrder.adjustView(mStartY, y, false);
                        musicMenuOrderChanged(endNumber);
                        startAdjustOrder(false);
                        break;
                }
                return false;
            }
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    private void addListener(final MusicMenuSimpleDisplay display) {
        display.getView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                display.setSelected(!display.getSelected());
                updateBottomTabState();
            }
        });
        display.getImageViewAdjust().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        display.getImageViewAdjust().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (mDisplay.size() > 1) {
                        mTargetNumber = getDisplayNumber(display);
                        startAdjustOrder(true);
                        mAdjustViewOrder = new AdjustViewOrder(new ArrayList<SimpleDisplayView>(mDisplay),
                                mTargetNumber, mAdjustOrderArea.getHeight());
                    }
                }
                return false;
            }
        });
        display.setCallBack(this);
    }

    //创建时更新视图
    private void updateView() {
        if (mFrom.equals(MusicListManageActivity.TAG)) {
            ((TextView) findViewById(R.id.textview_music_menu_manage_toolbar)).setText(R.string.select_music_menu);
            findViewById(R.id.button_music_menu_manage_recover).setVisibility(View.GONE);
            findViewById(R.id.linear_layout_delete_music_menu).setVisibility(View.GONE);
            mTextViewConfirm.setVisibility(View.VISIBLE);
        }
        updateBottomTabState();
    }

    //在第一个位置插入歌单项视图
    private void addNewMusicMenuView() {
        int listType = SimpleDisplayView.TYPE_DISPLAY;
        if (mFrom.equals(MusicMenuActivity.TAG))
            listType = SimpleDisplayView.TYPE_SELECT;
        if (mFrom.equals(MusicListManageActivity.TAG))
            listType = SimpleDisplayView.TYPE_CONFIRM;
        MusicMenuSimpleDisplay display = new MusicMenuSimpleDisplay(listType);
        RelativeLayout view = display.getView();
        mContainer.addView(view);
        mDisplay.add(display);
        addListener(display);
    }

    //更新歌单项展示视图
    private void updateMusicMenuView() {
        for (int i = 0; i < mMusicMenus.size(); i++) {
            MusicMenu musicMenu = mMusicMenus.get(i);
            updateMusicMenuView(musicMenu.getOrder(), musicMenu);
        }
        for (int i = 0; i < MusicPlayerSettings.getThreadLoadMenuCover(); i++) {
            updateMenuCover(i);
        }
    }

    //更新指定索引的视图
    private void updateMusicMenuView(int index, MusicMenu musicMenu) {
        if (index >= 0 && index < mDisplay.size())
            mDisplay.get(index).update(musicMenu);
    }

    //更新底部栏状态
    private void updateBottomTabState() {
        boolean flag = false;
        for (int i = 0; i < mDisplay.size(); i++)
            if (mDisplay.get(i).getSelected()) {
                flag = true;
                break;
            }
        mTextViewConfirm.setEnabled(flag);
        if (flag) {
            mTextViewConfirm.setBackgroundResource(R.drawable.selector_dialog_add_music);
            mTextViewConfirm.setTextColor(getResources().getColor(R.color.total_black));
        } else {
            mTextViewConfirm.setBackgroundResource(R.color.app_third_background_white);
            mTextViewConfirm.setTextColor(getResources().getColor(R.color.app_first_text_unenable));
        }
        mButtonDelete.setEnabled(flag);
        findViewById(R.id.textview_delete).setEnabled(flag);
    }

    //删除选定的歌单
    private void deleteMusicMenus() {
        List<MusicMenu> musicMenus = new ArrayList<MusicMenu>();
        int index = 0;
        for (int i = 0; i < mDisplay.size(); i++) {
            if (mDisplay.get(i).getSelected()) {
                musicMenus.add(mDisplay.get(i).getMusicMenu());
                mDisplay.remove(i);
                mContainer.removeViewAt(i);
                i--;
            }
            index++;
        }
        //若删除了歌单，则操作状态置为true
        if (musicMenus.size() > 0)
            mStateChanged = true;
        MusicInfo.deleteMusicMenu(musicMenus);
        updateBottomTabState();
    }

    //进入恢复歌单界面
    private void doClickRecover() {

    }

    //执行删除歌单操作
    private void doClickDelete() {
        if (mButtonDelete.isEnabled()) {
            String title = getString(R.string.title_delete_music_menu);
            String text = getString(R.string.text_delete_music_menu);
            final NormalAlertDialog dialog = new NormalAlertDialog(this, title, text);
            dialog.getCancel().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.getConfirm().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    deleteMusicMenus();
                    dialog.dismiss();
                }
            });
            dialog.show();
        }
    }

    //确认选择
    private void doClickConfirm() {
        if (mTextViewConfirm.isEnabled()) {
            List<String> menuName = new ArrayList<String>();
            for (int i = 0; i < mDisplay.size(); i++) {
                if (mDisplay.get(i).getSelected()) {
                    menuName.add(mDisplay.get(i).getMusicMenu().getName());
                }
            }
            //选择后返回上一个activity
            if (menuName.size() > 0) {
                mStateChanged = true;
                Intent intent = new Intent();
                intent.putExtra("result", mStateChanged);
                String[] array = new String[menuName.size()];
                for (int i = 0; i < array.length; i++)
                    array[i] = menuName.get(i);
                Bundle bundle = new Bundle();
                bundle.putStringArray(MusicListManageActivity.TAG_ARRAY, array);
                intent.putExtras(bundle);
                this.setResult(RESULT_CODE, intent);
                finish();
                setPendingTransition(R.anim.fake_anim, R.anim.activity_vertical_exit);
            } else {
                finishToBack();
            }
            finish();
            setPendingTransition(R.anim.fake_anim, R.anim.activity_vertical_exit);
        }
    }

    //处理歌单顺序的变化
    private void musicMenuOrderChanged(int endNumber) {
        if (mTargetNumber != endNumber) {
            //改变状态
            mStateChanged = true;
            if (mTargetNumber > endNumber) {
                for (int i = endNumber; i < mTargetNumber; i++) {
                    MusicMenu temp = mDisplay.get(i).getMusicMenu();
                    temp.setOrder(temp.getOrder() + 1);
                }
            } else {
                for (int i = endNumber; i > mTargetNumber; i--) {
                    MusicMenu temp = mDisplay.get(i).getMusicMenu();
                    temp.setOrder(temp.getOrder() - 1);
                }
            }
            MusicMenu temp = mDisplay.get(mTargetNumber).getMusicMenu();
            temp.setOrder(endNumber);
            MusicInfo.changeMusicMenuOrder();
            MusicMenuSimpleDisplay display = mDisplay.get(mTargetNumber);
            //调整歌单项的视图显示
            mDisplay.remove(mTargetNumber);
            mContainer.removeViewAt(mTargetNumber);
            mDisplay.add(endNumber, display);
            mContainer.addView(display.getView(), endNumber);
        }
    }

    //进入或离开调整顺序模式的处理
    private void startAdjustOrder(boolean isAdjust) {
        NewScrollView scrollView = findViewById(R.id.scroll_view_music_menu_manage);
        //设置scrollview不能滑动
        scrollView.setCanScroll(!isAdjust);
        mAdjustOrderArea.setClickable(isAdjust);
        int alpha = isAdjust ? 0 : 255;
        for (int i = 0; i < mDisplay.size(); i++) {
            //设置视图项透明
            mDisplay.get(i).setBackgroundAlpha(alpha);
            mDisplay.get(i).getView().setClickable(!isAdjust);
            mDisplay.get(i).getImageViewAdjust().setClickable(!isAdjust);
        }
    }

    //当前视图的编号
    private int getDisplayNumber(MusicMenuSimpleDisplay display) {
        for (int i = 0; i < mDisplay.size(); i++)
            if (mDisplay.get(i) == display)
                return i;
        return 0;
    }

    private void updateMenuCover(int position) {
        if (position < mDisplay.size()) {
            mDisplay.get(position).updateMenuCover();
        }
    }

    //退出activity
    private void finishToBack() {
        Intent intent = new Intent();
        intent.putExtra("result", mStateChanged);
        this.setResult(RESULT_CODE, intent);
    }

    @Override
    public void updateSuccess(int order) {
        updateMenuCover(order + MusicPlayerSettings.getThreadLoadMenuCover());
    }
}